<?php

namespace app\api\controller;

use app\admin\model\Community as CommunityModel;
use app\admin\model\Form1;
use app\admin\model\Form2;
use app\admin\model\Form3;
use app\admin\model\Poster;
use app\admin\model\Swiper;
use app\admin\model\Town;
use app\admin\model\ValidateCode;
use app\BaseController;
use app\common\controller\Sms;
use EasyAdmin\upload\Uploadfile;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;

class Common extends BaseController
{
    /**
     * 文件上传
     */
    public function upload()
    {
        $data = [
            'upload_type' => $this->request->post('upload_type'),
            'file'        => $this->request->file('file'),
        ];

        $uploadConfig = sysconfig('upload');
        empty($data['upload_type']) && $data['upload_type'] = $uploadConfig['upload_type'];
        $rule = [
            'upload_type|指定上传类型有误' => "in:{$uploadConfig['upload_allow_type']}",
            'file|文件'              => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$uploadConfig['upload_allow_size']}",
        ];
        $this->validate($data, $rule);

        try {
            $upload = Uploadfile::instance()
                ->setUploadType($data['upload_type'])
                ->setUploadConfig($uploadConfig)
                ->setFile($data['file'])
                ->save();
            if ($upload['save'] <> true) throw new Exception($upload['msg']);
        } catch (\Exception $e) {
            return result(0, $e->getMessage());
        }
        return result(1, $upload['msg'], ['id' => $upload['id'], 'url' => $upload['url']]);
    }

    /**
     * 获取滚动公告
     */
    public function getPosterList()
    {
        try {
            $list = Poster::column('content');
        } catch (\Exception $e) {
            return result(0, '获取失败：'.$e->getMessage());
        }
        return result(1, '获取成功', $list);
    }

    /**
     * 获取轮播图
     */
    public function getSwiperList()
    {
        try {
            $list = Swiper::field('name as title,url as image')->select();
        } catch (\Exception $e) {
            return result(0, '获取失败：'.$e->getMessage());
        }
        return result(1, '获取成功', $list);
    }

    /**
     * 获取乡镇信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getTownList()
    {
        $list = Town::getTownList();
        return result(1,'',$list);
    }

    /**
     * 获取社区
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCommunityList()
    {
        $list = CommunityModel::field('name as label,id as value')->select();
        foreach ($list as $k => &$v) {
            $v['extra'] = $k;
        }
        return result(1,'',$list);
    }

    /**
     * 购药人员-获取社区
     * @param string $town 乡镇ID
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCommunityList2()
    {
        $town = $this->request->param('town/d', 0);
        if ($town <> 1) {
            return result(1,'', [
                [
                    'value' =>  0,
                    'label' =>  '无',
                    'extra' =>  0,
                ],
            ]);
        }
        return self::getCommunityList();
    }

    /**
     * 发送验证码
     * @param string $mobile 手机号
     */
    public function sendSms()
    {
        try {
            $post = $this->request->post();
            $rule = [
                'mobile|手机号'    =>  'require|mobile',
            ];
            $this->validate($post, $rule);

            // 检测发送间隔
            if (Cache::get('interval_'.$post['mobile'])) {
                throw new Exception('发送间隔60秒，请稍后再试');
            }
            // 每日限制发5次
            if (ValidateCode::where('mobile', $post['mobile'])->whereDay('create_time')->count() >= 5) {
                throw new Exception('今日发送次数已超限，请明日再试');
            }

            // 构造6位数验证码
            $code = mt_rand(100000, 999999);
            $result = Sms::send(3, $post['mobile'], $code);

            if ($result == 'success' ) {
                // 插入验证码记录
                ValidateCode::create([
                    'mobile'    =>  $post['mobile'],
                    'code'      =>  $code,
                ]);
                // 验证码有效期5分钟
                Cache::set('valid_'.$post['mobile'], $code, 60 * 5);
                // 发送间隔60秒
                Cache::set('interval_'.$post['mobile'], $code, 60);
            } else {
                //日志记录
                Log::error($result);
                throw new Exception('发送失败：'.$result);
            }
        } catch (\Exception $e) {
            return result(0,$e->getMessage());
        }
        return result(1,'发送成功');
    }
}